<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="getTitle">
    <BasicForm @register="registerForm" :style="getBoxWidth" class="!mx-auto" />

    <template #footer>
      <Spin :spinning="loading" :delay="200">
        <ButtonActions
          v-if="!isCustom && buttons.length"
          @save="handleSubmit"
          @next="handleNext"
          @cancel="handleClose"
          @custom="handleBtnCustom"
          :data="buttons"
        />
        <div v-else>
          <a-button @click="handleSubmit" type="primary">保存</a-button>
          <a-button @click="handleClose">取消</a-button>
        </div>
      </Spin>
    </template>
    <ModelDesign :classify="2" :modelId="dataModelId" @success="init" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';

  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { Spin } from 'ant-design-vue';
  import { customFnForApi } from '../hooks/functionSet';
  import { useMessage } from '/@/hooks/web/useMessage';
  import ButtonActions from './ButtonActions.vue';
  import ModelDesign from './ShowModelDesign.vue';
  import { isObject } from '/@/utils/is';
  import { toJson, getCSSValue } from '/@/utils';
  import { UseModalInit } from '../hooks/useComFormModel';

  export default defineComponent({
    name: 'FormModal',
    components: { Spin, BasicModal, BasicForm, ButtonActions, ModelDesign },
    props: {
      isCustom: {
        type: Boolean,
        default: false,
      },
    },
    emits: ['success', 'next', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const loading = ref(false);
      const buttons = ref<any>([]);
      const dataModelId = ref('');
      const { createMessage } = useMessage();
      const modalInit = ref<Indexable>({});
      const [registerForm, formActionType] = useForm({
        baseColProps: { span: 23 },
        showActionButtonGroup: false,
      });
      const { resetFields, setProps: setFormProps } = formActionType;
      let rawData: Recordable = {};
      let title = ref('');
      let formWidth = ref('');
      const [registerModal, modalFn] = useModalInner(async (data) => {
        rawData = data;
        await init();
      });
      const { setModalProps, closeModal, changeLoading } = modalFn;

      const params = ref<Indexable>({});
      async function init() {
        const data = rawData;

        try {
          changeLoading(true);
          setModalProps({ confirmLoading: true });
          resetFields();
          isUpdate.value = !!data?.isUpdate;

          dataModelId.value = data.dataModelId;

          // 如果有数据则 不请求详情接口
          const retFormDesignInfo = data.retFormDesignInfo;

          const { complexParams = {} } = data._comParams || {};
          // 外层传递进入的窗口参数
          const dataParams = isObject(data.params) ? data.params : toJson(data.params);
          params.value = data.params = {
            ...dataParams,
            ...(complexParams.windowQuery || {}),
            ...(complexParams.windowParam || {}),
            ...(rawData.record || {}),
          };

          modalInit.value = new UseModalInit(
            { btnData: data as any, retFormDesignInfo },
            formActionType,
          );
          const {
            btns = [],
            title: name,
            padding,
            width,
            value,
          } = await modalInit.value.initialize();
          formWidth.value = width || '';
          title.value = name || '';
          buttons.value = btns.map((el) => Object.assign(el, data.params, value));
          setFormProps({
            baseRowStyle: { padding },
          });
        } catch (e) {
          throw e;
        } finally {
          setModalProps({ confirmLoading: false });
          changeLoading(false);
        }
      }

      const getTitle = computed(() => title.value || '');
      const getBoxWidth = computed(() => ({ width: getCSSValue(unref(formWidth), '100%') }));

      async function handleSubmit(flag = true) {
        try {
          // const values = await validate();
          loading.value = true;
          changeLoading(true);
          setModalProps({ confirmLoading: true });
          const [ret] = await modalInit.value.useModalSumbit(rawData.onlyData);
          createMessage.success('操作成功', 1.5);
          emit('success', ret, rawData);

          if (flag) {
            handleClose();
            return;
          }
          resetFields();
        } finally {
          loading.value = false;
          changeLoading(false);
          setModalProps({ confirmLoading: false });
        }
      }

      async function handleClose() {
        closeModal();
      }
      // todo next
      async function handleNext() {
        handleSubmit(!rawData.isCreate);
      }

      async function handleBtnCustom(btnConfig) {
        btnConfig.isForm = true;
        btnConfig.params = params.value;

        customFnForApi(btnConfig, {
          ...formActionType,
          //  弹框方法
          modalFn,
        });
      }
      return {
        init,
        getTitle,
        loading,
        buttons,
        dataModelId,
        getBoxWidth,
        registerModal,
        registerForm,
        handleSubmit,
        handleClose,
        handleBtnCustom,
        handleNext,
      };
    },
  });
</script>
